package org.example.servicelisten.listen;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.model.manage.bean.po.Student;
import org.example.servicelisten.service.SmsService;
import org.example.servicelisten.service.StudentService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@EnableAsync
public class ReportStatusListen {

    @Autowired
    private StudentService studentService;

    @Autowired
    private SmsService smsService;

    /**
     * 监听人脸检测历史消息队列
     * 消息格式: {"type": "face_detection", "timestamp": "2025-09-12T19:02:51.415587", 
     *           "data": {"faces": [{"bbox": [245, 75, 326, 184], "key": "000000000000000504", 
     *           "confidence": 0.4986106753349304, "distance": 0.5013893246650696}], 
     *           "frame_shape": [320, 240]}}
     */
    @RabbitListener(queues = "face_detection_history")
    public void receiveFaceDetectionMessage(String message) {
        try {
            log.info("接收到人脸检测消息: {}", message);
            
            // 解析JSON消息
            JSONObject jsonObject = JSON.parseObject(message);
            
            // 获取data字段
            JSONObject data = jsonObject.getJSONObject("data");
            if (data == null) {
                log.warn("消息中缺少data字段");
                return;
            }
            
            // 获取faces数组
            JSONArray faces = data.getJSONArray("faces");
            if (faces == null || faces.isEmpty()) {
                log.warn("消息中faces数组为空或不存在");
                return;
            }
            
            // 遍历faces数组，处理每个检测到的人脸
            for (int i = 0; i < faces.size(); i++) {
                JSONObject face = faces.getJSONObject(i);
                String key = face.getString("key");
                
                if (key != null && !key.isEmpty()) {
                    try {
                        // 将key转换为学生ID（假设key就是学生ID）
                        Integer studentId = Integer.valueOf(key);
                        
                        // 更新学生的report_check字段为1
                        boolean success = studentService.updateReportStatus(studentId, 1);
                        if (success) {
                            // 异步发送短信
                            //sendSmsAsync(studentId, reportCheck);
                            log.info("成功更新学生报道状态，学生ID: {}", studentId);
                        } else {
                            log.warn("更新学生报道状态失败，学生ID: {}", studentId);
                        }
                    } catch (NumberFormatException e) {
                        log.error("无法解析学生ID，key值: {}", key, e);
                    }
                } else {
                    log.warn("人脸数据中缺少key字段或key为空");
                }
            }
        } catch (Exception e) {
            log.error("处理人脸检测消息异常: {}", message, e);
        }
    }

    /**
     * 异步发送短信
     * @param studentId 学生ID
     * @param reportCheck 报到状态
     */
//    @Async
//    protected void sendSmsAsync(Integer studentId, Integer reportCheck) {
//        try {
//            // 查询学生信息
//            Student student = studentService.getById(studentId);
//            if (student != null && student.getTelephone() != null) {
//                String phone = student.getTelephone();
//                String status = reportCheck == 1 ? "已成功完成报到" : "未报到";
//                // 准备模板参数
//                Map<String, String> templateParams = new HashMap<>();
//                templateParams.put("status", status);
//                templateParams.put("name", student.getName());
//                smsService.sendSms(phone, templateParams);
//            } else {
//                log.error("无法获取学生手机号: 学生ID={}", studentId);
//            }
//        } catch (Exception e) {
//            log.error("发送短信异常: 学生ID={}", studentId, e);
//        }
//    }
}